package com.seabook.easymailservice;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import javax.mail.MessagingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class EasyMailServiceServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = -3463188934223298422L;
	
	private GeneralMailer generalMailer = new GeneralMailer();
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		// 1) parse the params from the request.
		String subject = req.getParameter(IRequestParam.SUBJECT);
		String from = req.getParameter(IRequestParam.FROM);
		String to = req.getParameter(IRequestParam.TO);
		String[] tos = new String[]{to};
		if (to != null && to.indexOf(",") != -1) {
			tos = to.split(",");
		}
		String cc = req.getParameter(IRequestParam.CC);
		String[] ccs = new String[]{cc};
		if (cc != null && cc.indexOf(",") != -1) {
			ccs = cc.split(",");
		}
		String isHtmlTxt = req.getParameter(IRequestParam.ISHTML);
		boolean isHtml = false;
		if ("y".equalsIgnoreCase(isHtmlTxt)) {
			isHtml = true;
		}
		String content = req.getParameter(IRequestParam.CONTENT);
		if (isHtml) {
			File file = new File(getServletContext().getRealPath("/html")) ;
			System.out.println(getServletContext().getRealPath("/html"));
			FileWriter fileWriter = new FileWriter(file);
			fileWriter.write(content);
			fileWriter.close();
		} 
		
		System.out.println("subject: " + subject);
		System.out.println("from: " + from);
		System.out.println("to: " + to);
		System.out.println("tos: " + tos);
		System.out.println("cc: " + cc);
		System.out.println("ccs: " + ccs);
		System.out.println("isHtml: " + isHtml);
		System.out.println("content: " + content);
		
		
		prepareGeneralMailer(subject, from, tos, ccs, isHtml, content);
		
		try {
			generalMailer.initDefaultMailSender();
			generalMailer.sendMessage();
		} catch (MessagingException e) {
			e.printStackTrace();
		}
	}

	private void prepareGeneralMailer(String subject, String from,
			String[] tos, String[] ccs, boolean isHtml, String content) {
		generalMailer.setSubject(subject);
		generalMailer.setFrom("ebay_work_mailbox@163.com");
		generalMailer.setTos(tos);
		generalMailer.setCcs(ccs);
		generalMailer.setHtml(isHtml);
		generalMailer.setContent(content);
	}

	
	
}
